#!/sbin/openrc-run
# Copyright 1999-2015 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2

extra_commands="checkconfig"
extra_started_commands="reload"

: ${SSHD_CONFDIR:=/etc/ssh}
: ${SSHD_CONFIG:=${SSHD_CONFDIR}/sshd_config}
: ${SSHD_PIDFILE:=/var/run/${SVCNAME}.pid}
: ${SSHD_BINARY:=/usr/sbin/sshd}

depend() {
	use logger dns
	if [ "${rc_need+set}" = "set" ] ; then
		: # Do nothing, the user has explicitly set rc_need
	else
		local x warn_addr
		for x in $(awk '/^ListenAddress/{ print $2 }' "$SSHD_CONFIG" 2>/dev/null) ; do
			case "${x}" in
				0.0.0.0|0.0.0.0:*) ;;
				::|\[::\]*) ;;
				*) warn_addr="${warn_addr} ${x}" ;;
			esac
		done
		if [ -n "${warn_addr}" ] ; then
			need net
			ewarn "You are binding an interface in ListenAddress statement in your sshd_config!"
			ewarn "You must add rc_need=\"net.FOO\" to your /etc/conf.d/sshd"
			ewarn "where FOO is the interface(s) providing the following address(es):"
			ewarn "${warn_addr}"
		fi
	fi
}

checkconfig() {
	if [ ! -d /var/empty ] ; then
		mkdir -p /var/empty || return 1
	fi

	if [ ! -e "${SSHD_CONFIG}" ] ; then
		eerror "You need an ${SSHD_CONFIG} file to run sshd"
		eerror "There is a sample file in /usr/share/doc/openssh"
		return 1
	fi

	ssh-keygen -A || return 1

	[ "${SSHD_PIDFILE}" != "/var/run/sshd.pid" ] \
		&& SSHD_OPTS="${SSHD_OPTS} -o PidFile=${SSHD_PIDFILE}"
	[ "${SSHD_CONFIG}" != "/etc/ssh/sshd_config" ] \
		&& SSHD_OPTS="${SSHD_OPTS} -f ${SSHD_CONFIG}"

	"${SSHD_BINARY}" -t ${SSHD_OPTS} || return 1
}

start() {
	checkconfig || return 1

	ebegin "Starting ${SVCNAME}"
	start-stop-daemon --start --exec "${SSHD_BINARY}" \
	    --pidfile "${SSHD_PIDFILE}" \
	    -- ${SSHD_OPTS}
	eend $?
}

stop() {
	if [ "${RC_CMD}" = "restart" ] ; then
		checkconfig || return 1
	fi

	ebegin "Stopping ${SVCNAME}"
	start-stop-daemon --stop --exec "${SSHD_BINARY}" \
	    --pidfile "${SSHD_PIDFILE}" --quiet
	eend $?
}

reload() {
	checkconfig || return 1
	ebegin "Reloading ${SVCNAME}"
	start-stop-daemon --signal HUP \
	    --exec "${SSHD_BINARY}" --pidfile "${SSHD_PIDFILE}"
	eend $?
}
